package com.hunantv.mglive.ui.live;

import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseFragment;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.ui.entertainer.ContributionView;
import com.hunantv.mglive.ui.entertainer.DynamicView;
import com.hunantv.mglive.ui.entertainer.FullAgreeView;
import com.hunantv.mglive.ui.entertainer.PersonValueView;
import com.hunantv.mglive.ui.entertainer.data.ContrData;
import com.hunantv.mglive.ui.entertainer.data.ContributionData;
import com.hunantv.mglive.ui.entertainer.data.ContributionInfoData;
import com.hunantv.mglive.ui.entertainer.data.PersonValueData;
import com.hunantv.mglive.ui.entertainer.listener.LoadmoreListener;
import com.hunantv.mglive.ui.entertainer.listener.PayContributionListener;
import com.hunantv.mglive.ui.live.detail.DetailConstants;
import com.hunantv.mglive.utils.GiftUtil;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.MGLiveMoneyUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.Toast.ConfirmDialog;

import org.json.JSONException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StarLiveDetailCentreFragment extends BaseFragment implements FullAgreeView.onFullDisplayListener {
    private static final String TAG = StarLiveDetailCentreFragment.class.getSimpleName();
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private LinearLayout dynmicLayout;//动态
    private LinearLayout personValueLayout;//在线
    private LinearLayout contributionLayout;//贡献
    //动态 人气 守护详细窗体  默认隐藏
    private FullAgreeView fullAgreeView;
    private StarModel mStarInfo;
    public TextView mHotValue;
    private DynamicView mDynamicView;
    private ImageView mIvDynamicIcon;
    //人气
    private PersonValueView mPersonValueView;
    private LoadmoreListener mPersonValueLoadmoreListener;
    private int mPersonValuePageSize = DetailConstants.DEFAULT_PAGE_SIZE;
    private String mPersonValueUrl = BuildConfig.URL_POPULARITY_RANK;
    private int mPersonValueCurrentPage = 1;
    private boolean mPersonValueHasMore = true;
    private boolean mPersonValueRequesting = false;
    //守护
    private ContributionView mContributionView;
    private int mGuardPageSize = DetailConstants.DEFAULT_PAGE_SIZE;
    private int mGuardCurrentPage = 1;
    private boolean mGuardHasMore = true;
    private boolean mGuardRequesting = false;
    private LoadmoreListener mGuardLoadmoreListener;
    private PayContributionListener mPayContributionListener;
    private ContributionInfoData contributionInfo;
    private View mDynView, mPersonView, mContrView;
    /**
     * VideoFragmnet 通信接口
     */
    private ICenterViewCallback mChangeCallback;

    public static StarLiveDetailCentreFragment newInstance(String param1, String param2) {
        StarLiveDetailCentreFragment fragment = new StarLiveDetailCentreFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public StarLiveDetailCentreFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_star_live_detail_centre, container, false);
        initListener();
        initCenterToobar(view);
        return view;
    }

    public StarModel getStarInfo() {
        return mStarInfo;
    }

    public void setStarInfo(StarModel mStarInfo) {
        this.mStarInfo = mStarInfo;
        String hotValue = !StringUtil.isNullorEmpty(mStarInfo.getHotValue()) ? mStarInfo.getHotValue() : mStarInfo.getHots();
        updateHotValue(hotValue);
        Object tagObj = fullAgreeView.getTag();
        if (tagObj instanceof DynamicView) {
            resetDynamic();
        } else if (tagObj instanceof PersonValueView) {
            resetPersonValue();
        } else if (tagObj instanceof ContributionView) {
            resetContribution();
        }
        if (fullAgreeView != null && fullAgreeView.isShow()) {
            fullAgreeView.closeView();
        }
        if (mIvDynamicIcon != null) {
            Glide.with(getActivity()).load(mStarInfo.getPhoto()).transform(new GlideRoundTransform(getActivity(), R.dimen.height_25dp)).error(R.drawable.default_icon).into(mIvDynamicIcon);
        }
    }

    /**
     * 中间区域
     */
    void initCenterToobar(View view) {
        View viewLl = view.findViewById(R.id.ll_live_star_detail_centre);
        RelativeLayout.LayoutParams ps = (RelativeLayout.LayoutParams) viewLl.getLayoutParams();
        //按比例缩放直播窗体
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels > dm.heightPixels ? dm.heightPixels : dm.widthPixels;
        ps.topMargin = (int) (width * 0.75);
        viewLl.setLayoutParams(ps);
        //动态
        dynmicLayout = (LinearLayout) view.findViewById(R.id.rl_live_star_detail_centre_dynmic);
        dynmicLayout.setOnClickListener(new CenterViewClickListen(CenterViewClickListen.CLICK_TYPE_DYNAMIC));
        mIvDynamicIcon = (ImageView) view.findViewById(R.id.iv_live_star_detail_centre_dynmic);

        //在线
        personValueLayout = (LinearLayout) view.findViewById(R.id.ll_live_star_detail_person_value);
        personValueLayout.setOnClickListener(new CenterViewClickListen(CenterViewClickListen.CLICK_TYPE_PERSON_VALUE));
        mHotValue = (TextView) personValueLayout.findViewById(R.id.tv_live_star_detail_personvalue);
        // 守护
        contributionLayout = (LinearLayout) view.findViewById(R.id.rl_live_star_detail_contribution);
        contributionLayout.setOnClickListener(new CenterViewClickListen(CenterViewClickListen.CLICK_TYPE_CONTRIBUTION));

        //动态 人气 守护详细窗体
        fullAgreeView = (FullAgreeView) view.findViewById(R.id.fullAgreeView);
        fullAgreeView.setFullListener(this);
        mDynamicView = new DynamicView(getActivity(), StarLiveDetailCentreFragment.this, fullAgreeView);
        mDynView = mDynamicView.getView();
        mDynView.setVisibility(View.GONE);
        fullAgreeView.addView(mDynView);

        mPersonValueView = new PersonValueView(getActivity(), fullAgreeView);
        mPersonValueView.setLoadMoreListener(mPersonValueLoadmoreListener);
        mPersonView = mPersonValueView.getView();
        mPersonView.setVisibility(View.GONE);
        fullAgreeView.addView(mPersonView);

        mContributionView = new ContributionView(getActivity(), fullAgreeView);
        mContributionView.setLoadMoreListener(mGuardLoadmoreListener);
        mContributionView.setPayContributionListener(mPayContributionListener);
        mContrView = mContributionView.getView();
        mContrView.setVisibility(View.GONE);
        fullAgreeView.addView(mContrView);
    }

    private void initListener() {
        mGuardLoadmoreListener = new LoadmoreListener() {
            @Override
            public void onLoadMore() {
                getContribution();
            }
        };

        mPersonValueLoadmoreListener = new LoadmoreListener() {
            @Override
            public void onLoadMore() {
                getPersonValue();
            }
        };

        mPayContributionListener = new PayContributionListener() {
            @Override
            public void payContribution(ContrData contrData) {
                payContr(contrData);
            }
        };
    }

    public void updateHotValue(String hotValue) {
        if (null != mHotValue) {
            mHotValue.setText(hotValue);
        }
    }

    @Override
    public void onfullChange(boolean change) {
        if (change) {
            if (mChangeCallback != null) {
                mChangeCallback.pauseVideo();
            }
        } else {
            if (mChangeCallback != null) {
                mChangeCallback.starVideo();
            }
            if (null != mDynamicView && null != mDynamicView.mDynamic) {
//                mDynamicView.mDynamic.mVideoTempView.pause();
            }
        }
    }

    /**
     * 设置videoFragment的回调函数
     *
     * @param changedCallback
     */
    public void setVideoViewListener(ICenterViewCallback changedCallback) {
        mChangeCallback = changedCallback;
    }

    /**
     * 中间toolbar点击事件
     */
    private class CenterViewClickListen implements View.OnClickListener {
        private int type;
        public static final int CLICK_TYPE_DYNAMIC = 1;//动态
        public static final int CLICK_TYPE_PERSON_VALUE = 2;//人气
        public static final int CLICK_TYPE_CONTRIBUTION = 3;//守护者

        public CenterViewClickListen(int type) {
            this.type = type;
        }

        @Override
        public void onClick(View v) {
            View view = null;
            if (type == CLICK_TYPE_DYNAMIC) {
                //动态
//                view = mDynamicView.getView();
                fullAgreeView.setTag(mDynamicView);
                mDynView.setVisibility(View.VISIBLE);
                mPersonView.setVisibility(View.GONE);
                mContrView.setVisibility(View.GONE);
                if (getActivity().getClass().getSimpleName().equals("StarDetailActivity")) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("c", "");
                }

            } else if (type == CLICK_TYPE_PERSON_VALUE) {
                //人气值
//                view = mPersonValueView.getView();
                fullAgreeView.setTag(mPersonValueView);
                mDynView.setVisibility(View.GONE);
                mPersonView.setVisibility(View.VISIBLE);
                mContrView.setVisibility(View.GONE);
                if (getActivity().getClass().getSimpleName().equals("StarDetailActivity")) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("c", "");
                }
            } else if (type == CLICK_TYPE_CONTRIBUTION) {
                //守护者
//                view = mContributionView.getView();
                fullAgreeView.setTag(mContributionView);
                mDynView.setVisibility(View.GONE);
                mPersonView.setVisibility(View.GONE);
                mContrView.setVisibility(View.VISIBLE);

                if (getActivity().getClass().getSimpleName().equals("StarDetailActivity")) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("c", "");
                }
            }
            if (!fullAgreeView.isShow()) {
//                fullAgreeView.removeAllViews();
//                fullAgreeView.addView(view);
                fullAgreeView.showView();

                getViewData(type);
            }
        }
    }

    private void getViewData(int type) {
        if (type == CenterViewClickListen.CLICK_TYPE_DYNAMIC) {
            //动态,没有切换艺人切有列表数据则不刷新
            if(mDynamicView.mDynamic.isEmptyData()){
                resetDynamic();
            }
        } else if (type == CenterViewClickListen.CLICK_TYPE_PERSON_VALUE) {
            //人气值
            mPersonValueCurrentPage = 1;
            mPersonValueRequesting = false;
            mPersonValueHasMore = true;
            getPersonValue();
        } else if (type == CenterViewClickListen.CLICK_TYPE_CONTRIBUTION) {
            //守护者
            mGuardCurrentPage = 1;
            mGuardRequesting = false;
            mGuardHasMore = true;
            getContribution();
        }
    }

    /**
     * 更换艺人之后重新获取动态
     */
    public void resetDynamic() {
        try {
            if (null != getStarInfo() && getStarInfo() != mDynamicView.mDynamic.getStarInfo()) {
                mDynamicView.mTitle.setText(getString(R.string.chat_dynamic, getStarInfo().getNickName()));
                mDynamicView.mDynamic.setStarInfo(getStarInfo());
                mDynamicView.mDynamic.resetData();
                mDynamicView.mDynamic.setIsSquareModle(false);
                mDynamicView.mDynamic.loadData();
            }

        } catch (Exception e) {

        }
    }

    //---------------------------守护-----------------------//
    public void getContribution() {
        Log.i(TAG, "getContribution, current:" + mGuardCurrentPage + ", size:" + mGuardPageSize + ", hasmore:" + mGuardHasMore + ", uid:" + getUid());
        if (null != mContributionView && mContributionView.mTitle != null && null != getStarInfo()) {
            mContributionView.mTitle.setText(getString(R.string.chat_shouhu, getStarInfo().getNickName()));
        }
        if (mGuardHasMore && !mGuardRequesting && mStarInfo != null) {
            mGuardRequesting = true;
            Log.d("守护page", mGuardCurrentPage + "");
            Map<String, String> body = new FormEncodingBuilderEx()
                    .add("page", String.valueOf(mGuardCurrentPage))
                    .add("pageSize", String.valueOf(mGuardPageSize))
                    .add("uid", mStarInfo.getUid())
                    .build();
            post(BuildConfig.URL_GUARD_RANK, body);

            loadContrList();

            loadContrInfo();
        }
    }

    private void resetContribution() {
        if (null != mContributionView && mContributionView.mTitle != null && null != getStarInfo()) {
            mContributionView.mTitle.setText(getString(R.string.chat_shouhu, getStarInfo().getNickName()));
        }
        mGuardCurrentPage = 1;
        mGuardRequesting = false;
        mGuardHasMore = true;
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("page", String.valueOf(mGuardCurrentPage))
                .add("pageSize", String.valueOf(mGuardPageSize))
                .add("uid", mStarInfo.getUid())
                .build();
        post(BuildConfig.URL_GUARD_RANK, body);
    }

    /**
     * 产品守护列表
     */
    private void loadContrList() {
        if (GiftUtil.getInstance().getContrs() == null)
        {
            Map<String, String> body = new FormEncodingBuilderEx().add("page", "1").add("pageSize", "10").build();
            post(BuildConfig.URL_CONTR_LIST, body);
        }else
        {
            mContributionView.setContrDatas(GiftUtil.getInstance().getContrs());
        }
    }

    /**
     * 查询守护信息
     */
    private void loadContrInfo() {
        if (isLogin() && mStarInfo != null && mContributionView != null) {
            Map<String, String> body = new FormEncodingBuilderEx()
                    .add("uid", getUid())
                    .add("token", getToken())
                    .add("aid", mStarInfo.getUid())
                    .build();
            L.d(TAG + "守护信息UID：", getUid());
            L.d(TAG + "守护信息STARID：", mStarInfo.getUid());
            post(BuildConfig.GET_CONTRIBUTION_INFO, body);
        }
    }

    public void payContr(final ContrData contrData) {
        String title = "成为" + mStarInfo.getNickName() + "的" + contrData.getName() + "支付" + contrData.getPrice() + "金币";
        final ConfirmDialog confirmDialog = new ConfirmDialog(getActivity(), title, "确认", "取消");
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                FormEncodingBuilderEx body = new FormEncodingBuilderEx();
                body.add("gid", contrData.getGid());
                body.add("count", "1");
                body.add("gift", "3");
                body.add("amount", contrData.getPrice() + "");
                body.add("buid", getUid());
                body.add("cuid", mStarInfo.getUid());
                body.add("token", getToken());
                if (getMqttClientId() != null) {
                    body.add("clientId", getMqttClientId());
                    body.add("flag", getMqttFlag());
                    body.add("key", getMqttKey());
                }
                body.add("tip", "");
                post(BuildConfig.PAY_GIFT, body.build());
                confirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                confirmDialog.cancel();
            }
        });

    }

    //---------------------------人气-----------------------//
    public void getPersonValue() {
        Log.i(TAG, "getPersonValue, current:" + mPersonValueCurrentPage + ", size:" + mPersonValuePageSize + ", hasmore:" + mPersonValueHasMore + ", uid:" + getUid());
        if (null != mPersonValueView && null != getStarInfo()) {
            mPersonValueView.mTitle.setText(getString(R.string.chat_hot_value, getStarInfo().getNickName()));
        }
        if (mPersonValueHasMore && !mPersonValueRequesting && mStarInfo != null) {
            mPersonValueRequesting = true;

            Log.d("人气page", mPersonValueCurrentPage + "");
            Map<String, String> body = new FormEncodingBuilderEx()
                    .add("page", String.valueOf(mPersonValueCurrentPage))
                    .add("pageSize", String.valueOf(mPersonValuePageSize))
                    .add("uid", mStarInfo.getUid())
                    .build();
            post(mPersonValueUrl, body);
        }
    }

    private void resetPersonValue() {
        if (null != mPersonValueView && null != getStarInfo()) {
            mPersonValueView.mTitle.setText(getString(R.string.chat_hot_value, getStarInfo().getNickName()));
        }
        mPersonValueCurrentPage = 1;
        mPersonValueRequesting = false;
        mPersonValueHasMore = true;

        Map<String, String> body = new FormEncodingBuilderEx()
                .add("page", String.valueOf(mPersonValueCurrentPage))
                .add("pageSize", String.valueOf(mPersonValuePageSize))
                .add("uid", mStarInfo.getUid())
                .build();
        post(mPersonValueUrl, body);
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
//        Log.i(TAG, "onSucceed url:" + url);
        try {
            if (url.equals(BuildConfig.URL_GUARD_RANK)) {
                getGuardSuccess(resultModel);

            } else if (url.equals(mPersonValueUrl)) {
                getPersonValueSuccess(resultModel);

            } else if (BuildConfig.URL_CONTR_LIST.equals(url)) {
                GiftUtil.getInstance().setContrs(JSON.parseArray(resultModel.getData(), ContrData.class));
                mContributionView.setContrDatas( GiftUtil.getInstance().getContrs());
            } else if (BuildConfig.PAY_GIFT.equals(url)) {
                Toast.makeText(getContext(), "守护成功", Toast.LENGTH_SHORT).show();
            } else if (BuildConfig.GET_CONTRIBUTION_INFO.equals(url)) {
                contributionInfo = JSON.parseObject(resultModel.getData(), ContributionInfoData.class);
                mContributionView.setContrInfo(contributionInfo);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
//        Log.i(TAG, "onFailure url:" + url);
        if (BuildConfig.GET_CONTRIBUTION_INFO.equals(url)) {
            mContributionView.setContrInfo(null);
        } else {
            Toast.makeText(getActivity(), resultModel.getMsg(), Toast.LENGTH_SHORT).show();
        }
        if (BuildConfig.PAY_GIFT.equals(url) && ResultModel.ERROR_CODE_GOLD_ENOUGH.equals(resultModel.getCode())) {

            MGLiveMoneyUtil.getInstance().goMGLiveMonneyPay(getActivity());

        }
        if (BuildConfig.URL_GUARD_RANK.equals(url)) {
            mGuardRequesting = false;
        }
    }

    @Override
    public void onError(String url, Exception e) {
        super.onError(url, e);
    }

    @Override
    public void onResume() {
        loadContrInfo();
        super.onResume();
    }

    private void getGuardSuccess(ResultModel resultModel) throws JSONException {
//        Log.i(TAG, "getGuardSuccess");

        if (resultModel == null) {
            Log.e(TAG, "resultModel null");
            mContributionView.setShowDefault(true);
            return;
        }

        String resultJson = resultModel.getData();
        if (resultJson == null) {
            Log.e(TAG, "resultModel null");
            mContributionView.setShowDefault(true);
            return;
        }

        List<ContributionData> results = JSON.parseArray(resultModel.getData(), ContributionData.class);

        if (mContributionView != null) {

            if (mGuardCurrentPage == 1) {
                mContributionView.setDatas(results);
                mContributionView.resetSelection();

            } else {
                mContributionView.addDatas(results);

            }
        }
        mGuardCurrentPage++;
        L.d("守护结果", results.size() + "");
        if (results.size() < mGuardPageSize) {
            mGuardHasMore = false;
        }

        mGuardRequesting = false;
    }

    private void getPersonValueSuccess(ResultModel resultModel) throws JSONException {
        Log.i(TAG, "getPersonValueSuccess");

        if (resultModel == null) {
            Log.e(TAG, "resultModel null");
            return;
        }

        String resultJson = resultModel.getData();
        if (resultJson == null) {
            Log.e(TAG, "resultModel null");
            return;
        }

        List<PersonValueData> results = JSON.parseArray(resultModel.getData(), PersonValueData.class);

        if (mPersonValueView != null) {

            if (mPersonValueCurrentPage == 1) {
                mPersonValueView.setDatas(results);

            } else {
                mPersonValueView.addDatas(results);
            }
        }
        mPersonValueCurrentPage++;
        L.d("人气结果", results.size() + "");
        if (results.size() < mPersonValuePageSize) {
            mPersonValueHasMore = false;
        }

        mPersonValueRequesting = false;
    }

    public boolean onBackPressed() {
        if (fullAgreeView.isShow()) {
            fullAgreeView.closeView();
            return true;
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mDynamicView) {
            mDynamicView.mDynamic.onDestroy();
        }
        mChangeCallback = null;
    }

    @Override
    public void onPause() {
        if (null != mDynamicView) {
//            mDynamicView.mDynamic.onPause();
        }
        super.onPause();
    }

    public interface ICenterViewCallback {
        void pauseVideo();

        void starVideo();
    }
}